import { query } from '../../lib/db';
import { AppointmentSchema } from '../../lib/schema';

export default async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        const { date } = req.query;
        if (!date) {
          return res.status(400).json({ error: 'Date parameter is required' });
        }
        
        // 获取指定日期的所有预约
        const appointments = await query(
          'SELECT * FROM appointments WHERE appointment_date = $1 ORDER BY time_slot', 
          [date]
        );
        
        // 获取所有可用时间段
        const timeSlots = await query(
          'SELECT DISTINCT time_slot FROM appointments WHERE appointment_date = $1',
          [date]
        );
        
        return res.status(200).json({
          appointments: appointments.rows,
          availableSlots: timeSlots.rows
        });
        
      case 'POST':
        // 验证输入数据
        const validation = AppointmentSchema.safeParse(req.body);
        if (!validation.success) {
          return res.status(400).json({
            error: 'Invalid input',
            details: validation.error.flatten()
          });
        }
        
        const { name, phone, wechat, email, date, timeSlot, notes } = validation.data;
        
        // 检查时间段是否已被预约
        const existing = await query(
          'SELECT 1 FROM appointments WHERE appointment_date = $1 AND time_slot = $2',
          [date, timeSlot]
        );
        
        if (existing.rows.length > 0) {
          return res.status(409).json({ error: 'Time slot already booked' });
        }
        
        // 创建新预约
        const result = await query(
          `INSERT INTO appointments 
          (name, phone, wechat, email, appointment_date, time_slot, notes)
          VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
          [name, phone, wechat, email, date, timeSlot, notes]
        );
        
        return res.status(201).json(result.rows[0]);
        
      default:
        res.setHeader('Allow', ['GET', 'POST']);
        return res.status(405).end(`Method ${req.method} Not Allowed`);
    }
  } catch (err) {
    console.error('API Error:', err);
    return res.status(500).json({ 
      error: 'Internal server error',
      details: process.env.NODE_ENV === 'development' ? {
        message: err.message,
        stack: err.stack
      } : undefined
    });
  }
}